package com.kaifamiao.wendao.controller;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Explain;
import com.kaifamiao.wendao.entity.Thumbs;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.service.ExplainService;
import com.kaifamiao.wendao.service.ThumbsService;
import com.kaifamiao.wendao.utils.Constants;
import org.tinylog.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/explain/*")
public class ExplainServlet extends HttpServlet {

    private ExplainService explainService;
    private ThumbsService thumbsService;

    @Override
    public void init() throws ServletException {
        explainService = new ExplainService();
        thumbsService=new ThumbsService();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getMethod();
        String uri = request.getRequestURI();
        // POST "/explain/publish"
        if ("POST" .equals(method) && uri.endsWith("/publish") ){
            this.publishAction(request,response);
            return;
        }

        // POST "/explain/remove"
        if ("GET" .equals(method) && uri.endsWith("/remove") ){
            this.removeAction(request,response);
            return;
        }
        if("GET".equals(method) && uri.endsWith("/praise")){
            this.praise(request,response);
            return;
        }
        if("GET".equals(method) && uri.endsWith("/despise")){
            this.despise(request,response);
            return;
        }
    }

    private boolean validatePublish(HttpServletRequest request){


        return true;
    }
    // POST "/explain/publish"
    protected void publishAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        HttpSession session = request.getSession();
        Customer c = (Customer)session.getAttribute(Constants.CUSTOMER_LOGINED);
        String tid = request.getParameter("topicId");
        System.out.println(tid);

        if (this.validatePublish(request)){

            Long topicId = Long.valueOf(tid);
            System.out.println(topicId);
            Topic t = new Topic();
            t.setId(topicId);
            String content = request.getParameter("content");
            System.out.println(content);
            String addr = request.getRemoteAddr();

            Explain e = new Explain();
            e.setContent(content);
            e.setPublishAddress(addr);
            e.setAuthor(c);
            e.setTopic(t);
            try {
                if (explainService.save(e)) {
                    response.sendRedirect(request.getContextPath()+"/topic/detail?id=" + tid);
                    return;
                }
            } catch (Exception ex) {
                Logger.error(ex);
            }
            session.setAttribute("message", "保存失败");
            session.setAttribute("content", content);
        }
        response.sendRedirect(request.getContextPath() + "/topic/"+tid+"/explain");

        }

    protected void removeAction(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        String uri = request.getRequestURI();
        Pattern p = Pattern.compile("\\d{19}");
        Matcher m = p.matcher(uri);
        if (m.find()) {
            String sid = m.group();
            Long id = Long.valueOf(sid);
            String eeid = request.getParameter("id");
            Long eid = Long.valueOf(eeid);
            explainService.remove(eid);
            response.sendRedirect(request.getContextPath() + "/topic/detail?id="+id);
        }
    }
    protected void praise(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{

        HttpSession session=request.getSession();
        Customer customer=(Customer) session.getAttribute("customer");
        String idString=request.getParameter("id");
        Long id=Long.valueOf(idString);
        Thumbs t=thumbsService.findCidEid(id,customer.getId());
        System.out.println(t);
        if(t==null){
            Thumbs th=new Thumbs();
            th.setCustomer_id(customer.getId());
            th.setExplain_id(id);
            thumbsService.save(th);
        }
        Thumbs th=thumbsService.findCidEid(id,customer.getId());
        Long operation=th.getOperation();
        session.setAttribute("operation",operation);
        if(operation==0){
            Explain e=explainService.load(id);
            e.setPraise(e.getPraise()+1);
            th.setOperation(th.getOperation()+2);
            th.setCustomer_id(customer.getId());
            explainService.update(e);
            thumbsService.update(th);
            response.sendRedirect(request.getContextPath()+"/topic/detail");
            return;
        }
        if(operation==2){
            Explain e=explainService.load(id);
            e.setPraise(e.getPraise()-1);
            th.setOperation(th.getOperation()-2);
            explainService.update(e);
            thumbsService.update(th);
            response.sendRedirect(request.getContextPath()+"/topic/detail");
            return;
        }

        if(operation==1){
            Explain e=explainService.load(id);
            e.setDespise(e.getDespise()-1);
            e.setPraise(e.getPraise()+1);
            explainService.update(e);
            th.setOperation(th.getOperation()+1);
            thumbsService.update(th);
            response.sendRedirect(request.getContextPath()+"/topic/detail");
        }
    }

    protected void despise(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        HttpSession session=request.getSession();
        Customer customer=(Customer) session.getAttribute("customer");
        String idString=request.getParameter("id");
        System.out.println(idString);
        Long id=Long.valueOf(idString);
        Thumbs t=thumbsService.findCidEid(id,customer.getId());

        if(t==null){
            Thumbs th=new Thumbs();
            th.setCustomer_id(customer.getId());
            th.setExplain_id(id);
            thumbsService.save(th);
        }
        Thumbs th=thumbsService.findCidEid(id,customer.getId());
        Long operation=th.getOperation();
        session.setAttribute("operation",operation);
        if(operation==0){
            Explain e=explainService.load(id);
            e.setDespise(e.getDespise()+1);
            th.setOperation(th.getOperation()+1);
            explainService.update(e);
            thumbsService.update(th);
            response.sendRedirect(request.getContextPath()+"/topic/detail");
            return;
        }
        if(operation==1){
            Explain e=explainService.load(id);
            e.setDespise(e.getDespise()-1);
            th.setOperation(th.getOperation()-1);
            explainService.update(e);
            thumbsService.update(th);
            response.sendRedirect(request.getContextPath()+"/topic/detail");
            return;
        }
        if(operation==2){
            Explain e=explainService.load(id);
            e.setPraise(e.getPraise()-1);
            e.setDespise(e.getDespise()+1);
            explainService.update(e);
            th.setOperation(th.getOperation()-1);
            thumbsService.update(th);
            response.sendRedirect(request.getContextPath()+"/topic/detail");
        }
    }

}
